<template>
	<view class="">
		<tn-nav-bar fixed :isBack="true" :bottomShadow="false">
			微信登录
		</tn-nav-bar>
		<view class="container" :style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<view class="wechatapp">
				<view class="header">
					<!-- <open-data class="avatar" type="userAvatarUrl"></open-data> -->
					<image class="image"
						:src="storeInfo && storeInfo.image_url ? storeInfo.image_url : '/static/default-avatar.png'">
					</image>
				</view>
			</view>
			<view class="auth-title">申请获取以下权限</view>
			<view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view>
			<view class="login-btn">
				<!-- 获取微信用户信息 -->
				<button class="button btn-normal" @click.stop="getUserProfile">授权登录</button>
			</view>
			<view class="no-login-btn">
				<button class="button btn-normal" @click="handleCancel">暂不登录</button>
			</view>
		</view>
		<tn-popup v-model="show" mode="center" :maskCloseable="false">
		  <view class="btn-Phone-h">
		  	<!-- #ifdef MP-WEIXIN -->
		  	<MpWeixinMobile :isheight="false" :isParty="isParty" :partyData="partyData" />
		  	<!-- #endif -->
		  </view>
		</tn-popup>


	</view>
</template>

<script>
	import store from '@/store'
	import {
		isEmpty
	} from '@/utils/util'
	import SettingModel from '@/common/model/Setting'
	import MpWeixinMobile from './mp-weixin-mobile'

	export default {
		components: {
			MpWeixinMobile
		},
		props: {
			// 是否存在第三方用户信息
			isParty: {
				type: Boolean,
				default: () => false
			},
			// 第三方用户信息数据
			partyData: {
				type: Object
			}
		},
		data() {
			return {
				show:false,
				// 商城基本信息
				storeInfo: '',
				// 微信小程序登录凭证 (code)
				// 提交到后端，用于换取openid
				code: ''
			}
		},
		created() {
			// 获取商城基本信息
			this.getStoreInfo()
		},

		methods: {

			// 获取商城基本信息
			getStoreInfo() {
				SettingModel.item('store').then((res) => {
					this.storeInfo = res
				})
			},

			// 获取code
			// https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
			getCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: res => {
							resolve(res.code)
						},
						fail: reject
					})
				})
			},

			// 获取微信用户信息(新版)
			getUserProfile() {
				const app = this
				wx.canIUse('getUserProfile') && wx.getUserProfile({
					lang: 'zh_CN',
					desc: '获取用户相关信息',
					success({
						userInfo
					}) {
						// 授权成功事件
						app.onAuthSuccess(userInfo)
					},
					fail() {
						console.log(91)
					}
				})
			},

			// 授权成功事件
			// 这里分为两个逻辑:
			// 1.将code和userInfo提交到后端，如果存在该用户 则实现自动登录，无需再填写手机号
			// 2.如果不存在该用户, 则显示注册页面, 需填写手机号
			// 3.如果后端报错了, 则显示错误信息
			async onAuthSuccess(userInfo) {
				const app = this
				// 提交到后端
				store.dispatch('LoginMpWx', {
						partyData: {
							code: await app.getCode(),
							oauth: 'MP-WEIXIN',
							userInfo
						},
						refereeId: store.getters.refereeId
					})
					.then(result => {
						if(result.status == 500){
							if (result.data.isBindMobile) {
								// app.onEmitSuccess(userInfo)
								app.show = true
							}
						}else{
							// 一键登录成功
							app.$toast(result.message)
							// 相应全局事件订阅: 刷新上级页面数据
							uni.$emit('syncRefresh', true)
							// 跳转回原页面
							setTimeout(() => app.onNavigateBack(2), 2000)
						}
					})
			},

			// 将oauth提交给父级
			// 这里要重新获取code, 因为上一次获取的code不能复用(会报错)
			async onEmitSuccess(userInfo) {
				const app = this
				app.$emit('success', {
					oauth: 'MP-WEIXIN', // 第三方登录类型: MP-WEIXIN
					code: await app.getCode(), // 微信登录的code, 用于换取openid
					userInfo // 微信用户信息
				})
			},
			/**
			 * 暂不登录
			 */
			handleCancel() {
				// 跳转回原页面
				this.onNavigateBack()
			},

			/**
			 * 登录成功-跳转回原页面
			 */
			onNavigateBack(delta = 1) {
				const pages = getCurrentPages()
				if (pages.length > 1) {
					uni.navigateBack({
						delta: Number(delta || 1)
					})
				} else {
					this.$navTo('pages/index')
				}
			}

		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 0 60rpx;
		font-size: 32rpx;
		background: #fff;
		min-height: 100vh;
	}

	.wechatapp {
		padding: 80rpx 0 48rpx;
		border-bottom: 1rpx solid #e3e3e3;
		margin-bottom: 72rpx;
		text-align: center;

		.header {
			width: 190rpx;
			height: 190rpx;
			border: 4rpx solid #fff;
			margin: 0 auto 0;
			border-radius: 50%;
			overflow: hidden;
			box-shadow: 2rpx 0 10rpx rgba(50, 50, 50, 0.3);

			.image {
				display: block;
				width: 100%;
				height: 100%;
			}
		}
	}

	.auth-title {
		color: #585858;
		font-size: 34rpx;
		margin-bottom: 40rpx;
	}

	.auth-subtitle {
		color: #888;
		margin-bottom: 88rpx;
		font-size: 28rpx;
	}
	
	.btn-Phone-h{
		width: 600rpx;
		height: 160rpx;
		display: flex;
		justify-content: center;
	}
	
	.btn-Phone {
		height: 88rpx;
		background: #04be01;
		color: #fff;
		font-size: 30rpx;
		border-radius: 999rpx;
		width: 400rpx;
	}

	.login-btn {
		padding: 0 20rpx;

		.button {
			height: 88rpx;
			background: #04be01;
			color: #fff;
			font-size: 30rpx;
			border-radius: 999rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}


	.no-login-btn {
		margin-top: 20rpx;
		padding: 0 20rpx;

		.button {
			height: 88rpx;
			background: #dfdfdf;
			color: #fff;
			font-size: 30rpx;
			border-radius: 999rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>